<!--
 * @Author: shiweizhen 787632169@qq.com
 * @Date: 2025-06-25 10:07:13
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-06-30 16:35:06
 * @Description: 
 * Copyright (c) 2025-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
  <DtDialog v-model="visible" :loading="loading" :is-loading="isLoading" :title="formData.id ? '编辑' : '新增'"
    @close="handleClose()" @confirm="handleSubmit()">
    <el-form ref="formDataRef" :model="formData" label-width="100px" :rules="rules">
      <el-form-item label="excel名称" prop="name">
        <el-input v-model.trim="formData.name" />
      </el-form-item>
      <el-form-item label="excel描述" prop="description">
        <el-input v-model.trim="formData.description" />
      </el-form-item>
    </el-form>
  </DtDialog>
</template>

<script lang="ts" setup>
import { FormInstance } from 'element-plus';
import { getCurrentInstance, ref, Ref } from 'vue'
import { DtDialog } from 'hbisdt-design';
import { ExcelType } from '@/api/dashbord/types';
import { editExcel, saveExcel } from '@/api/dashbord';
const vm = getCurrentInstance()!
const { useDialog, $modal } = vm.appContext.config.globalProperties
const emits = defineEmits(['close'])
/**
 * 定义表单ref
 */
const formDataRef = ref<FormInstance | null>(null);
const { visible, isLoading, loading, openDialog, closeDialog, submitLoading, cancelLoading } = useDialog(formDataRef as Ref<FormInstance>)
const formData = ref<ExcelType>({
  name: '',
  description: ''
})
const rules = {
  name: [
    {
      required: true,
      message: '请输入excel名称',
      trigger: 'blur'
    }
  ],
}
const handleOpen = (data?: ExcelType): void => {
  if (data) {
    formData.value = data
  } else {
    formData.value = {
      name: '',
      description: ''
    }
  }
  openDialog()
}
const handleClose = (): void => {
  closeDialog()
}
const handleSubmit = (): void => {
  formDataRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading()
      if (formData.value.id) {
        await editExcel(formData.value)
        $modal.msgSuccess('编辑成功')
      } else {
        await saveExcel(formData.value)
        $modal.msgSuccess('新增成功')
      }
      emits('close')
      cancelLoading()
      handleClose()
    }
  })

}

defineExpose({
  handleOpen
})
</script>